<template>
  <div id="addUserDialog">
    <el-dialog
      class="about-set"
      :title="showTitle"
      :visible.sync="dialogData.isShow"
      width="510px"
      :before-close="labelHandleClose"
    >
      <div class="form-box">
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"
          label-width="90px"
          class="demo-ruleForm"
        >
          <el-form-item label="导入方式" prop="type">
            <el-select v-model="ruleForm.type" placeholder="请选择">
              <el-option
                v-for="item in typeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <!--此处不用v-if,因为切换后，会不显示大鹏号，而显示userId-->
          <div :class="ruleForm.type === '1' ? 'hideClass' : ''">
            <el-form-item label="大鹏号" prop="dpNum">
              <el-select
                v-model="ruleForm.dpNum"
                multiple
                filterable
                remote
                :no-data-text="noData"
                placeholder="请输入大鹏号"
                :remote-method="remoteMethod"
                :loading="inputLoading"
                clearable
              >
                <el-option
                  v-for="item in options"
                  :key="item.userId"
                  :label="item.dpNumber"
                  :value="item.userId"
                  :disabled="ruleForm.dpNum.length >= 5"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </div>
          <div :class="ruleForm.type === '0' ? 'hideClass' : ''">
            <importFile
              :file-data="fileData"
              :dialog-data="importDialogData"
            ></importFile>
          </div>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="success" plain @click="cancelLabel">取 消</el-button>
        <el-button
          type="success"
          :loading="loading"
          @click="confirmLabel('ruleForm')"
          >确认</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { downloadUrl } from '@/api/system/user' // 接口
import { importUserLabel } from '@/api/lableManage/labelUser' // 接口
import { getDpNum } from '@/api/system/user' // 接口
import importFile from '@component/lableManage/common/importFile' // 导入
export default {
  name: 'AddUserDialog',
  msg: '标签管理-添加用户弹窗',
  components: {
    importFile
  },
  props: ['dialogData'],
  data() {
    return {
      showTitle: '添加用户',
      loading: false,
      inputLoading: false,
      tagId: '', //标签id
      fileData: {
        labelName: '批量导入', // label名称
        fileName: '', // 上传文件名称
        upFile: '' // 上传文件
      },
      // 传递给导入弹框的数据
      importDialogData: {
        downUrl: '' // 下载模板接口
      },
      typeList: [
        // 导入方式列表
        { label: '手动输入', value: '0' },
        { label: '批量导入', value: '1' }
      ],
      ruleForm: {
        type: '0', // 导入方式
        dpNum: [] // 大鹏号
      },
      options: [], // 大鹏号下拉列表
      noData: '请再输入至少10个字符',
      rules: {
        dpNum: { required: true, message: '大鹏号不能为空', trigger: 'blur' }
      }
    }
  },
  watch: {
    'ruleForm.type': {
      handler(newV, oldV) {
        if (newV === '0') {
          //手动输入
          this.rules.dpNum.required = true
        } else {
          //批量导入
          this.rules.dpNum.required = false
        }
      },
      deep: true
    }
  },
  mounted() {
    this.tagId = this.dialogData.tagId
    this.importDialogData.downUrl = downloadUrl()
  },
  methods: {
    labelHandleClose(done) {
      this.cancelLabel()
      done()
    },
    cancelLabel() {
      // 关闭前清空
      this.loading = false
      this.dialogData.isShow = false
      this.dialogData.tagId = ''
    },
    /*获取大鹏号*/
    getDapengNum(dpAccounts) {
      return new Promise((resolve, reject) => {
        let obj = { type: 'DPACCOUNT', value: dpAccounts }
        getDpNum(
          obj,
          (response) => {
            resolve(response)
          },
          (response) => {
            this.$message.warning(response.message)
            resolve([])
          }
        )
      })
    },
    /*输入框内容改变时，执行*/
    async remoteMethod(query) {
      /* console.log("query",query)*/
      query = query.trim()
      let _this = this
      if (query.length > 9) {
        _this.inputLoading = true
        let result = await this.getDapengNum(query)
        let ary = result.rows
        if (ary.length === 0) {
          setTimeout(() => {
            _this.options = []
            _this.inputLoading = false
            this.noData = '没有找到匹配大鹏号'
          }, 200)
        } else {
          setTimeout(() => {
            _this.options = [...ary]
            _this.inputLoading = false
            /* console.log("this.options=",this.options)*/
          }, 200)
        }
      } else {
        _this.options = []
        let n = 10 - query.length
        this.noData = `请再输入${n}个字符`
      }
    },
    /* 确认提交 */
    confirmLabel(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //手动输入
          if (this.ruleForm.type === '0') {
            this.subHand()
          } else {
            // 批量导入
            if (!this.fileData.fileName) {
              this.$message({
                message: '请添加文件！',
                type: 'warning'
              })
              return
            }
            this.subImport()
          }
        } else {
          return false
        }
      })
    },
    /* 提交表单-批量导入 */
    subImport() {
      this.loading = true
      let formData = new FormData()
      formData.append('file', this.fileData.upFile)
      formData.append('ids', [this.tagId])
      importUserLabel(
        formData,
        (response) => {
          this.loading = false
          this.$emit('refresh')
          this.cancelLabel()
        },
        (response) => {
          // 有上传失败的情况，弹出失败提示窗
          this.loading = false
          this.$emit('showError', response.message, 'tagManageDp', response)
          this.cancelLabel()
        }
      )
    },
    /* 提交表单-手动导入 */
    subHand() {
      //手动导入
      this.loading = true
      let obj = {
        userIds: this.ruleForm.dpNum
      }
      importUserLabel(
        obj,
        (response) => {
          this.loading = false
          this.$emit('refresh')
          this.cancelLabel()
        },
        (response) => {
          // 上传失败
          this.loading = false
          this.$message.warning('新增失败,' + response.message)
        },
        `?tagId=${this.tagId}`
      )
    }
  }
}
</script>

<style lang="less">
#addUserDialog {
  .hideClass {
    display: none;
  }
  .el-autocomplete {
    width: 100%;
  }
  .el-dialog__body {
    padding-bottom: 10px !important;
  }
}
</style>
